<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Collection;
use App\Models\Department;
use App\Models\Position;
use App\Models\Resume;
use App\Models\Staff;
use App\Models\User;
use DB;
use Illuminate\Http\Request;
use Validator;

class PositionController extends Controller {
	private $role_flag;
	private $user;
	public function __construct() {
		if (\Auth::guard('api')->check()) {
			$getUser = \Auth::guard('api')->user();
			$user = User::find($getUser->id);
			if (!$this->getDevice()) {
				//app
				$user->company_id = $user->appcompany_id;
			}
			$this->user = $user;
			$company = \App\Models\Company::find($this->user->company_id);
			$this->role_flag = $company->role_flag;
		}
	}
	public function all(Request $request) {
		$type = $request->input('type');
		if (empty($type)) {
			$type = 1;
		}
		if (!in_array($type, [1, 2])) {
			return $this->respond('empty_error');
		}
		$company_id = $this->user->company_id;
		$root = Department::where(['company_id' => $company_id, 'depth' => 1])->first();
		$get_node = Department::find($root->id);
		$node = $get_node->getDescendantsAndSelf(['id', 'name'])->toArray();
		$page = $this->page($request);
		$query = DB::table('positions as a')->join('users as b', 'a.user_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id, 'a.is_use' => 1]);
		if ($type == 1) {
			//1:模糊查询
			$name = $request->input('name');
			$dept_name = $request->input('deptName');
			$edu = $request->input('edu');
			if (!empty($name) || $name == '0') {
				$query->where('a.name', 'like', '%' . $name . '%');
			}
			if (!empty($dept_name)) {
				$query->where('a.dept_name', '=', $dept_name);
			}
			if (!empty($edu)) {
				$query->where('a.edu', '=', $edu);
			}
		}
		if ($type == 2) {
			//2:高级搜素
			$keyword = $request->input('keyword');
			$query->where(function ($query) use ($keyword) {
				if (!empty($keyword) || $keyword == '0') {
					$query->orwhere('a.address', 'like', '%' . $keyword . '%');
					$query->orwhere('a.name', 'like', '%' . $keyword . '%');
					$query->orwhere('a.experience', 'like', '%' . $keyword . '%');
					$query->orwhere('a.edu', 'like', '%' . $keyword . '%');
				}
			});
		}
		$total_item = $query->select('a.*', 'b.name as owner_name')->orderBy('a.id', 'desc')->get();
		if (empty($total_item)) {
			return $this->respond('get_ok', ['item' => [], 'step' => $steps, 'count' => 0, 'pageNum' => 0]);
		}
		$item = array_slice($total_item->toArray(), $page['skip'], $page['take']);
		$count = count($total_item);
		$data['count'] = $count;
		$pageNum = ceil($count / $page['take']);
		$data['pageNum'] = $pageNum;
		$data['item'] = $item;
		$data['dept'] = $node;
		return $this->respond('get_ok', $data);
	}
	//pc职位首页
	public function getAll(Request $request) {
		$type = $request->input('type');
		$company_id = $this->user->company_id;
		$page = $this->page($request);
		$query = DB::table('positions as a')->join('users as b', 'a.user_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id]);
		$name = $request->input('name');
		if (!empty($name) || $name == '0') {
			$query->where('a.name', 'like', '%' . $name . '%');
		}
		$deptName = $request->input('deptName');
		if (!empty($deptName)) {
			$query->where('a.dept_name', '=', $deptName);
		}
		$person = $request->input('person');
		if (!empty($person)) {
			$query->where('a.person', '=', $person);
		}
		$total_item = $query->select('a.*', 'b.name as owner_name')->orderBy('a.id', 'desc')->get();
		if (empty($total_item)) {
			return $this->respond('get_ok', ['item' => [], 'count' => 0, 'pageNum' => 0]);
		}
		if ($type == 1) {
			return $this->respond('get_ok', ['item' => $total_item]);
		}
		$item = array_slice($total_item->toArray(), $page['skip'], $page['take']);
		$count = count($total_item);
		$data['count'] = $count;
		$pageNum = ceil($count / $page['take']);
		$data['pageNum'] = $pageNum;
		$data['item'] = $item;
		return $this->respond('get_ok', $data);
	}
	//新增保存
	public function add(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$roleType = $request->input('roleType');
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if ($roleType == 1) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('position_add') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('position_add')) {
					return $this->respond('no_auth');
				}
			}
			return $this->respond('op_ok');
		}
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('position_add') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('position_add')) {
				return $this->respond('no_auth');
			}
		}
		$validator = Validator::make($request->all(), Position::$rules, Position::$message);
		if ($validator->fails()) {
			return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
		}
		$m = new Position();
		$m->user_id = $this->user->id;
		$m->company_id = $this->user->company_id;
		$m->type = $request->input('type');
		$m->name = $request->input('name');
		$m->address = $request->input('address');
		$m->nature = $request->input('nature');
		$m->min_salary = $request->input('minSalary');
		$m->max_salary = $request->input('maxSalary');
		$m->edu = $request->input('edu');
		$m->dept_name = $request->input('deptName');
		$m->person = $request->input('person');
		$m->experience = $request->input('experience');
		$m->demand = $request->input('demand');
		$m->duty = $request->input('duty');
		$m->number = $request->input('number') ?? 1;
		$result = $m->save();
		if ($result) {
			return $this->respond('add_ok');
		}
		return $this->respond('add_error');
	}
	//获取单条记录
	public function get($id) {
		$model = DB::table('positions as a')->join('users as b', 'a.user_id', '=', 'b.id')->where(['a.status' => 0, 'a.id' => $id])->select('a.*', 'b.name as owner_name')->first();
		if (!empty($model)) {
			$collection_status = Collection::where(['user_id' => $this->user->id, 'company_id' => $this->user->company_id, 'obj_id' => $id, 'type' => 2, 'status' => 0])->first();
			$model->cstatus = $collection_status ? 1 : 0;
			$company = \App\Models\Company::where(['status' => 0, 'id' => $model->company_id])->select('id', 'name')->first();
			$model->company_name = '';
			if (!empty($company)) {
				$model->company_name = $company->name;
			}
			return $this->respond('get_ok', $model);
		}
		return $this->respond('get_error');
	}
	//更新保存
	public function put(Request $request, $id) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		$roleType = $request->input('roleType');
		if ($roleType == 1) {
			if (!empty($staff) && $staff->company_id == $user->company_id) {
				if (!$user->can('position_edit') && !$user->hasRole('管理员')) {
					return $this->respond('no_auth');
				}
			} else {
				if (!$user->can('position_edit')) {
					return $this->respond('no_auth');
				}
			}
			return respond('op_ok');
		}
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('position_edit') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('position_edit')) {
				return $this->respond('no_auth');
			}
		}
		if (empty($id)) {
			return response()->json(['code' => 500, 'msg' => '职位id不能为空']);
		}
		$validator = Validator::make($request->all(), Position::$rules, Position::$message);
		if ($validator->fails()) {
			return response()->json(['code' => 500, 'msg' => $validator->errors()->first()]);
		}
		$model = new Position();
		$m = $model::find($id);
		if (empty($model)) {
			return $this->respond('get_error');
		}
		$is_use = $request->input('isUse');
		if (empty($is_use)) {
			$is_use = 1;
		}
		if (!in_array($is_use, [1, 2])) {
			return response()->json(['code' => 500, 'msg' => '状态类型参数为空或无效']);
		}
		$m->type = $request->input('type');
		$m->name = $request->input('name');
		$m->address = $request->input('address');
		$m->nature = $request->input('nature');
		$m->min_salary = $request->input('minSalary');
		$m->max_salary = $request->input('maxSalary');
		$m->edu = $request->input('edu');
		$m->dept_name = $request->input('deptName');
		$m->person = $request->input('person');
		$m->experience = $request->input('experience');
		$m->demand = $request->input('demand');
		$m->duty = $request->input('duty');
		$m->is_use = $is_use;
		$m->number = $request->input('number') ?? 1;
		//开启事务
		DB::beginTransaction();
		try {
			//中间逻辑代码
			$m->save();
			if ($is_use == 2) {
				//关闭职位同时取消简历的关联关系
				Resume::where(['company_id' => $user->company_id, 'status' => 0])->where('position_id', $id)->update(['position_id' => 0]);
			}
			DB::commit();
			return $this->respond('update_ok', ['id' => $id]);
		} catch (\Exception $e) {
			//接收异常处理并回滚
			DB::rollBack();
			return $this->respond('update_error');
		}
	}
	//删除职位
	public function remove(Request $request) {
		$user = $this->user;
		$user->guard_name = $this->role_flag;
		$staff = \App\Models\Staff::where(['status' => 0, 'mobile' => $user->mobile, 'role_status' => 1])->first();
		if (!empty($staff) && $staff->company_id == $user->company_id) {
			if (!$user->can('position_remove') && !$user->hasRole('管理员')) {
				return $this->respond('no_auth');
			}
		} else {
			if (!$user->can('position_remove')) {
				return $this->respond('no_auth');
			}
		}
		$id = $request->input('id');
		if (empty($id) || !is_array($id)) {
			return $this->respond('empty_error');
		}
		//开启事务
		DB::beginTransaction();
		try {
			//中间逻辑代码
			Position::whereIn('id', $id)->update(['status' => 1]); //删除职位
			Resume::where(['company_id' => $user->company_id, 'status' => 0])->whereIn('position_id', $id)->update(['position_id' => 0]);
			DB::commit();
			return $this->respond('delete_ok');
		} catch (\Exception $e) {
			//接收异常处理并回滚
			DB::rollBack();
			return $this->respond('delete_error');
		}
	}
	public function deptName(Request $request) {
		$company_id = $this->user->company_id;
		$root = Department::where(['company_id' => $company_id, 'depth' => 1])->first();
		$get_node = Department::find($root->id);
		$node = $get_node->getDescendantsAndSelf(['id', 'name'])->toArray();
		return $this->respond('get_ok', $node);
	}
	public function deptUser(Request $request) {
		$company_id = $this->user->company_id;
		$data = Staff::where(['company_id' => $company_id, 'status' => 0])->select('name')->get();
		return $this->respond('get_ok', $data);
	}
	public function getName(Request $request) {
		$company_id = $this->user->company_id;
		$name = $request->input('name');
		$query = Department::where(['company_id' => $company_id]);
		if (!empty($name)) {
			$name = trim($name);
			$query->where('name', 'like', '%' . $name . '%');
		}
		$data = $query->select('id', 'name')->orderBy('depth', 'desc')->get();
		return $this->respond('get_ok', $data);
	}
	//获取职位关联的简历
	public function list(Request $request) {
		$type = $request->input('type');
		$positionId = $request->input('positionId');
		if (empty($positionId)) {
			return $this->respond('empty_error');
		}
		$company_id = $this->user->company_id;
		$page = $this->page($request);
		//待启动
		$query1 = DB::table('resumes as a')->join('users as b', 'a.owner_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id, 'a.position_id' => $positionId]);
		//统计数值
		$count1 = $query1->where(function ($query) {
			$query->where('a.step_id', 0)->orWhere('a.check_status', 2)->orWhere('a.ask_status', 2);
		})->count('a.id');
		//初审
		$query2 = DB::table('resumes as a')->join('users as b', 'a.owner_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id, 'a.position_id' => $positionId]);
		$count2 = $query2->where(function ($query) {
			$query->where('a.step_id', 1);
			$query->where(function ($query) {
				$query->where('a.check_status', 0)->orWhere('a.check_status', 3);
			});
		})->count('a.id');
		//面试
		$query3 = DB::table('resumes as a')->join('users as b', 'a.owner_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id, 'a.position_id' => $positionId]);
		$count3 = $query3->where(function ($query) {
			$query->where([['a.step_id', '>', 3], ['a.ask_status', '!=', 2], ['a.check_status', '!=', 2]]);
		})->count('a.id');
		//offer
		$query4 = DB::table('resumes as a')->join('users as b', 'a.owner_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id, 'a.position_id' => $positionId]);
		$count4 = $query4->where(function ($query) {
			$query->where('a.step_id', 2);
			$query->where(function ($query) {
				$query->where('a.check_status', 0)->orWhere('a.check_status', 3);
			});
		})->count('a.id');
		//待入职
		$query5 = DB::table('resumes as a')->join('users as b', 'a.owner_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id, 'a.position_id' => $positionId]);
		$count5 = $query5->where(function ($query) {
			$query->where('a.step_id', 3);
			$query->where(function ($query) {
				$query->where('a.check_status', 0)->orWhere('a.check_status', 3);
			});
		})->count('a.id');
		//已入职
		$query6 = DB::table('resumes as a')->join('users as b', 'a.owner_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id, 'a.position_id' => $positionId]);
		$count6 = $query6->where(['a.step_id' => 3, 'a.check_status' => 1])->count('a.id');

		$query = DB::table('resumes as a')->join('users as b', 'a.owner_id', '=', 'b.id')->where(['a.status' => 0, 'a.company_id' => $company_id, 'a.position_id' => $positionId]);
		$type = $type ?? 1;
		if ($type == 1) {
			//待启动
			$query->where(function ($query) {
				$query->where('a.step_id', 0)->orWhere('a.check_status', 2)->orWhere('a.ask_status', 2);
			});

		} else if ($type == 2) {
			//初审
			$query->where('a.step_id', 1);
			$query->where(function ($query) {
				$query->where('a.check_status', 0)->orWhere('a.check_status', 3);
			});
		} else if ($type == 3) {
			//面试
			$query->where([['a.step_id', '>', 3], ['a.ask_status', '!=', 2], ['a.check_status', '!=', 2]]);
		} else if ($type == 4) {
			//offer
			$query->where('a.step_id', 2);
			$query->where(function ($query) {
				$query->where('a.check_status', 0)->orWhere('a.check_status', 3);
			});
		} else if ($type == 5) {
			//待入职
			$query->where('a.step_id', 3);
			$query->where(function ($query) {
				$query->where('a.check_status', 0)->orWhere('a.check_status', 3);
			});
		} else if ($type == 6) {
			//已入职
			$query->where(['a.step_id' => 3, 'a.check_status' => 1])->where('a.is_job', '!=', 4);
		}
		$total_item = $query->select('a.*', 'b.name as owner_name')->orderBy('a.id', 'desc')->get();
		if (empty($total_item)) {
			return $this->respond('get_ok', ['item' => [], 'count' => 0, 'pageNum' => 0]);
		}
		$item = array_slice($total_item->toArray(), $page['skip'], $page['take']);
		$count = count($total_item);
		$data['totalCount'] = [$count1, $count2, $count3, $count4, $count5, $count6];
		$data['count'] = $count;
		$pageNum = ceil($count / $page['take']);
		$data['pageNum'] = $pageNum;
		$data['item'] = $item;
		return $this->respond('get_ok', $data);
	}
}
